# coding: utf-8
'''
Description: 
version: 1.0.0
Author: peng2.zhang
Date: 2021-10-25 11:56:09
LastEditors: peng2.zhang
LastEditTime: 2022-05-07 15:55:47
'''
import re
import yaml
import requests
from datetime import datetime
from urllib.parse import urljoin
from ci_conclude.const import CODE, EUREKA, JenkinsUser
from ci_conclude.base import BaseConclude
from ci_conclude.git_manage import GitManage
from ci_conclude.git_parser import GitParser
from ci_conclude.jenkins_manage import JenkinsManage
from ci_conclude.eureka_manage import EurekaManage

class HeadlineConclude(BaseConclude):
    # def __init__(self, *args, **kwargs):
    #     super(HeadlineConclude, self).__init__(*args, **kwargs)
    #     self.componentKeys = self.component = self.project_name
    #     if kwargs.get("git_name"):
    #         self.git_name = kwargs.get("git_name")
    #     else:
    #         self.git_name = self.project_name.split("stdci_std-")[1]

    def get_git_project_id(self, *args, **kwargs):
        token = self.git_token or "V6w6ocyhWTN8gax1q6aw"
        url = GitManage.url
        search_url = urljoin(url, f"api/v4/projects?search={self.search_git_name}")
        headers = {"PRIVATE-TOKEN": token}
        res = requests.get(search_url, headers=headers)
        search_list = res.json()
        if len(search_list) > 0:
            git_json = [i for i in search_list if i["name"] == self.git_name or i["ssh_url_to_repo"] == self.git_name or i["http_url_to_repo"] == self.git_name][0]
            git_project_id = git_json["id"]
            return git_project_id
        else:
            raise ValueError()

    def get_url(self):
        return self.jenkins_url
    
    def get_result(self):
        """
            集成Jenkins、Gitlab、Eureka结果
        """
        # 获取Jenkins结果
        jenkinsManage = JenkinsManage(username=JenkinsUser.DEFAULT.NAME, password=JenkinsUser.DEFAULT.PASS)
        job_status = jenkinsManage.job_status(self.project_name, self.buildid)
        job_duration = jenkinsManage.job_duration(self.project_name, self.buildid)
        build_username = jenkinsManage.get_build_username(self.project_name, self.buildid)
        # 获取Gitlab结果
        # projectID = self.get_git_project_id()
        # try:
        #     gitManage = GitManage(self.git_name, git_commit_id=self.git_commit_id, git_branch_name=self.git_branch_name, git_token=self.git_token)
        #     branch = gitManage.getLatestBranch()
        #     commit = gitManage.getLatestCommit()

        #     git_branch_name = branch["name"]
        #     git_commit_id = commit.short_id
        #     # 提交者
        #     committer_email = commit.committer_email
        #     git_commit_by = committer_email.split("@")[0]
        #     # 提交信息
        #     git_commit_message = commit.message.strip()
        #     # from code import interact
        #     # interact(local=locals())
        #     git_commit_time = datetime.strptime(commit.committed_date.split(".")[0], "%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d %H:%M:%S")
        # except ValueError:
        g = GitParser(self.project_name, self.buildid)
        print(g.git_commit_branch)
        print(g.git_commit_user)
        print(g.git_commit_id)
        print(g.git_commit_time)
        git_branch_name = g.git_commit_branch
        git_commit_id = g.git_commit_id
        # 提交者
        committer_email = f"{g.git_commit_user}@ecarxgroup.com" 
        git_commit_by = g.git_commit_user
        # 提交信息
        git_commit_message = ''
        git_commit_time = g.git_commit_time
        # from code import interact
        # interact(local=locals())
        #except ValueError:
        #    git_branch_name = ''
        #    git_commit_id = ''
        #    # 提交者
        #    committer_email = ''
        #    git_commit_by = ''
        #    # 提交信息
        #    git_commit_message = ''
        #    # from code import interact
        #    # interact(local=locals())
        #    git_commit_time = '1999-01-01 00:00:00'
        # 获取Eureka结果
        eureka_addr = getattr(EUREKA, self.product.upper()).NAME
        eurekaManage = EurekaManage(eureka_addr, self.eureka_app_name)
        eureka_status = eurekaManage.get_server_status()
        eureka_status = ";".join(eureka_status)
        eureka_versions = eurekaManage.get_server_version()
        eureka_version = ";".join(eureka_versions)

        data = {
            "job_name": self.project_name,
            "build_id": self.buildid,
            "job_status": job_status,  # Jenkins 执行结果
            "job_duration": job_duration,  # Jenkins 构建历时
            "build_username": build_username,  # GitLab 提交commit_id
            "git_commit_branch": git_branch_name,  # GitLab 构建分支
            "git_commit_id": git_commit_id,  # GitLab 提交commit_id
            "git_commit_by": git_commit_by,  # GitLab 提交者
            "git_commit_message": git_commit_message,  # GitLab 提交信息
            "git_commit_time": git_commit_time,  # GitLab 提交信息
            "eureka_version": eureka_version,  # Eureka 构建服务版本
            "eureka_status": eureka_status,  # Eureka 构建服务版本
        }
        if job_status == "SUCCESS":
            result = dict(code=CODE.PASS.ID, message=CODE.PASS.NAME, data=data)
        else:
            result = dict(code=CODE.FAIL.ID, message=CODE.PASS.NAME, data=data)
        print(result)
        return result

    def format_to_weixin(self, result_kwargs, url):
        if result_kwargs["data"]["git_commit_time"] == "1999-01-01 00:00:00":
            git_commit_time = ""
        else:
            git_commit_time = result_kwargs["data"]["git_commit_time"]
        duration = result_kwargs["data"]["job_duration"]
        minutes = int(duration/60)
        seconds = int(duration%60)
        format_duration = f"{minutes}m:{seconds}s"
        if result_kwargs["data"]["git_commit_id"]:
            content = (f"""\n ## [Build Report]  [报告地址]({url}) """
            f"""\n > [构建任务]: <font color="comment">{self.project_name}</font> """
            f"""\n > [构建结果]: <font color="{'info' if result_kwargs["data"]["job_status"].upper() == "SUCCESS" else 'warning'}">{result_kwargs["data"]["job_status"]}</font> """
            f"""\n > [构建者]: <font color="comment">{result_kwargs["data"]["build_username"]}</font> """
            f"""\n > [业务版本]: <font color="comment">{result_kwargs["data"]["eureka_version"]}</font> """
            f"""\n > [git rev]: <font color="comment">{result_kwargs["data"]["git_commit_id"]}</font> """
            f"""\n > [提交者]: <font color="comment">{result_kwargs["data"]["git_commit_by"]}</font> """
            f"""\n > [提交时间]: <font color="comment">{result_kwargs["data"]["git_commit_time"]}</font> """
            f"""\n > [代码分支]: <font color="comment">{result_kwargs["data"]["git_commit_branch"]}</font> """
            f"""\n > [构建历时]: <font color="comment">{format_duration}</font> """)
        else:
            content = (f"""\n ## [Build Report]  [报告地址]({url}) """
            f"""\n > [构建任务]: <font color="comment">{self.project_name}</font> """
            f"""\n > [构建结果]: <font color="{'info' if result_kwargs["data"]["job_status"].upper() == "SUCCESS" else 'warning'}">{result_kwargs["data"]["job_status"]}</font> """
            f"""\n > [构建者]: <font color="comment">{result_kwargs["data"]["build_username"]}</font> """
            f"""\n > [业务版本]: <font color="comment">{result_kwargs["data"]["eureka_version"]}</font> """
            f"""\n > [构建历时]: <font color="comment">{format_duration}</font> """)
        print(content)
        return content
